Part B: Question 8.9

  • use rpart() and prune(); do not use tree() and cv.tree().
  • set.seed(1237)

Dataset

oj <- OJ

a

Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.

set.seed(1237)
train <- sample(1:nrow(oj), 800)

oj.train <- oj[train,]
oj.test <- oj[-train,]
nrow(oj.train)
## [1] 800
nrow(oj.test)
## [1] 270

b

Fit a tree to the training data, with Purchase as the response and the other variables as predictors. Use the summary() function to produce summary statistics about the tree, and describe the results obtained. What is the training error rate? How many terminal nodes does the tree have?

What variables are predictors:

names(oj)
##  [1] "Purchase"       "WeekofPurchase" "StoreID"        "PriceCH"       
##  [5] "PriceMM"        "DiscCH"         "DiscMM"         "SpecialCH"     
##  [9] "SpecialMM"      "LoyalCH"        "SalePriceMM"    "SalePriceCH"   
## [13] "PriceDiff"      "Store7"         "PctDiscMM"      "PctDiscCH"     
## [17] "ListPriceDiff"  "STORE"

Creating the tree:

oj.rpart0 <- rpart(Purchase ~ WeekofPurchase + StoreID + PriceCH + PriceMM + DiscCH + DiscMM + SpecialCH + SpecialMM + LoyalCH + SalePriceMM + SalePriceCH + PriceDiff + Store7 + PctDiscMM + PctDiscCH + ListPriceDiff + STORE,
                   data = oj.train)

printcp(oj.rpart0) # display the results 
## 
## Classification tree:
## rpart(formula = Purchase ~ WeekofPurchase + StoreID + PriceCH + 
##     PriceMM + DiscCH + DiscMM + SpecialCH + SpecialMM + LoyalCH + 
##     SalePriceMM + SalePriceCH + PriceDiff + Store7 + PctDiscMM + 
##     PctDiscCH + ListPriceDiff + STORE, data = oj.train)
## 
## Variables actually used in tree construction:
## [1] ListPriceDiff LoyalCH       PctDiscCH    
## 
## Root node error: 308/800 = 0.385
## 
## n= 800 
## 
##         CP nsplit rel error  xerror     xstd
## 1 0.519481      0   1.00000 1.00000 0.044685
## 2 0.016234      1   0.48052 0.49351 0.036026
## 3 0.010000      4   0.42208 0.48377 0.035751
# summary(oj.rpart0) # detailed summary of splits
# plotcp(oj.rpart0)  # visualize cross-validation results 

# multiple ways to calculate the training error rate:
class.pred <- table(predict(oj.rpart0, type="class"), oj.train$Purchase)
1-sum(diag(class.pred))/sum(class.pred)
## [1] 0.1625
0.385*0.42208
## [1] 0.1625008

We can see that the training error rate is 16.25%, and 5 nodes from 4 splits.

c

Type in the name of the tree object in order to get a detailed text output. Pick one of the terminal nodes, and interpret the information displayed.

oj.rpart0
## n= 800 
## 
## node), split, n, loss, yval, (yprob)
##       * denotes terminal node
## 
##  1) root 800 308 CH (0.61500000 0.38500000)  
##    2) LoyalCH>=0.450956 514  85 CH (0.83463035 0.16536965)  
##      4) LoyalCH>=0.705699 296  16 CH (0.94594595 0.05405405) *
##      5) LoyalCH< 0.705699 218  69 CH (0.68348624 0.31651376)  
##       10) ListPriceDiff>=0.235 134  22 CH (0.83582090 0.16417910) *
##       11) ListPriceDiff< 0.235 84  37 MM (0.44047619 0.55952381)  
##         22) PctDiscCH>=0.052007 12   2 CH (0.83333333 0.16666667) *
##         23) PctDiscCH< 0.052007 72  27 MM (0.37500000 0.62500000) *
##    3) LoyalCH< 0.450956 286  63 MM (0.22027972 0.77972028) *
# summary(oj.rpart0)

We can see from this output that at terminal node #3 the observations are tested for LoyalCH< 0.450956; 286 observations from the training dataset end up at this node and 63 are misclassified.

d

Create a plot of the tree, and interpret the results.

Borrowing some code from the script provided in class:

plot(oj.rpart0, uniform=TRUE, main="Regression Tree for Purchase ")
text(oj.rpart0, use.n=TRUE, all=TRUE, cex=.8)

This plot shows more clearly what is tabulated in the results from part c; namely that there are 5 nodes, and four splits.

e

Predict the response on the test data, and produce a confusion matrix comparing the test labels to the predicted test labels. What is the test error rate?

pred.oj.rpart0 <- predict(oj.rpart0,
                          newdata = oj.test,
                          type = "class")
confusionMatrix(pred.oj.rpart0, oj.test$Purchase)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 132  24
##         MM  29  85
##                                           
##                Accuracy : 0.8037          
##                  95% CI : (0.7512, 0.8494)
##     No Information Rate : 0.5963          
##     P-Value [Acc > NIR] : 2.768e-13       
##                                           
##                   Kappa : 0.5953          
##                                           
##  Mcnemar's Test P-Value : 0.5827          
##                                           
##             Sensitivity : 0.8199          
##             Specificity : 0.7798          
##          Pos Pred Value : 0.8462          
##          Neg Pred Value : 0.7456          
##              Prevalence : 0.5963          
##          Detection Rate : 0.4889          
##    Detection Prevalence : 0.5778          
##       Balanced Accuracy : 0.7998          
##                                           
##        'Positive' Class : CH              
## 
1-0.8037
## [1] 0.1963

The test error rate is \(1-0.8037 = 0.1963\).

f

Apply the cv.tree() function to the training set in order to determine the optimal tree size.

We will use prune() instead of cv.tree, to determine the optima tree size:

# prune the tree for min CV error
pfit<- prune(oj.rpart0, 
             cp = oj.rpart0$cptable[which.min(oj.rpart0$cptable[,"xerror"]),"CP"])
pfit
## n= 800 
## 
## node), split, n, loss, yval, (yprob)
##       * denotes terminal node
## 
##  1) root 800 308 CH (0.61500000 0.38500000)  
##    2) LoyalCH>=0.450956 514  85 CH (0.83463035 0.16536965)  
##      4) LoyalCH>=0.705699 296  16 CH (0.94594595 0.05405405) *
##      5) LoyalCH< 0.705699 218  69 CH (0.68348624 0.31651376)  
##       10) ListPriceDiff>=0.235 134  22 CH (0.83582090 0.16417910) *
##       11) ListPriceDiff< 0.235 84  37 MM (0.44047619 0.55952381)  
##         22) PctDiscCH>=0.052007 12   2 CH (0.83333333 0.16666667) *
##         23) PctDiscCH< 0.052007 72  27 MM (0.37500000 0.62500000) *
##    3) LoyalCH< 0.450956 286  63 MM (0.22027972 0.77972028) *

g

Produce a plot with tree size on the x-axis and cross-validated classification error rate on the y-axis.

par(mfrow=c(1,3)) # three plots on one page 

#This produces the first plot, asked for in part g
plotcp(pfit)

# This produces the other plots of number of splits vs R2 & X-relative error
rsq.rpart(pfit) # visualize cross-validation results 
## 
## Classification tree:
## rpart(formula = Purchase ~ WeekofPurchase + StoreID + PriceCH + 
##     PriceMM + DiscCH + DiscMM + SpecialCH + SpecialMM + LoyalCH + 
##     SalePriceMM + SalePriceCH + PriceDiff + Store7 + PctDiscMM + 
##     PctDiscCH + ListPriceDiff + STORE, data = oj.train)
## 
## Variables actually used in tree construction:
## [1] ListPriceDiff LoyalCH       PctDiscCH    
## 
## Root node error: 308/800 = 0.385
## 
## n= 800 
## 
##         CP nsplit rel error  xerror     xstd
## 1 0.519481      0   1.00000 1.00000 0.044685
## 2 0.016234      1   0.48052 0.49351 0.036026
## 3 0.010000      4   0.42208 0.48377 0.035751
## Warning in rsq.rpart(pfit): may not be applicable for this method

h

Which tree size corresponds to the lowest cross-validated classification error rate?

As we can see from the first plot above a tree size of 5 (i.e. 4 splits) results in the lowest CV error rate

i

Produce a pruned tree corresponding to the optimal tree size obtained using cross-validation. If cross-validation does not lead to selection of a pruned tree, then create a pruned tree with five terminal nodes.

As we can see from the above results, the tree produced by the prune() function has 5 terminal nodes and has the optimal cross-validated error.

j

Compare the training error rates between the pruned and unpruned trees. Which is higher?

par(mfrow=c(1,3)) # three plots on one page 

plot(oj.rpart0, uniform=TRUE, main="Regression Tree for Purchase ")
text(oj.rpart0, use.n=TRUE, all=TRUE, cex=.8)

plot(pfit, uniform=TRUE, main="PrunedRegression Tree for Purchase ")
text(pfit, use.n=TRUE, all=TRUE, cex=.8)

As we can see from the above plot, the pruned and unpruned trees are identical. We can calculate their training error rates:

#unpruned training error rate:
class.pred <- table(predict(oj.rpart0, type="class"), oj.train$Purchase)
1-sum(diag(class.pred))/sum(class.pred)
## [1] 0.1625
#pruned training error rate:
class.pred <- table(predict(pfit, type="class"), oj.train$Purchase)
1-sum(diag(class.pred))/sum(class.pred)
## [1] 0.1625

As expected, they are identical.

k

Compare the test error rates between the pruned and unpruned trees. Which is higher?

pred.pfit <- predict(pfit,
                          newdata = oj.test,
                          type = "class")
confusionMatrix(pred.oj.rpart0, oj.test$Purchase)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 132  24
##         MM  29  85
##                                           
##                Accuracy : 0.8037          
##                  95% CI : (0.7512, 0.8494)
##     No Information Rate : 0.5963          
##     P-Value [Acc > NIR] : 2.768e-13       
##                                           
##                   Kappa : 0.5953          
##                                           
##  Mcnemar's Test P-Value : 0.5827          
##                                           
##             Sensitivity : 0.8199          
##             Specificity : 0.7798          
##          Pos Pred Value : 0.8462          
##          Neg Pred Value : 0.7456          
##              Prevalence : 0.5963          
##          Detection Rate : 0.4889          
##    Detection Prevalence : 0.5778          
##       Balanced Accuracy : 0.7998          
##                                           
##        'Positive' Class : CH              
## 
confusionMatrix(pred.pfit, oj.test$Purchase)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 132  24
##         MM  29  85
##                                           
##                Accuracy : 0.8037          
##                  95% CI : (0.7512, 0.8494)
##     No Information Rate : 0.5963          
##     P-Value [Acc > NIR] : 2.768e-13       
##                                           
##                   Kappa : 0.5953          
##                                           
##  Mcnemar's Test P-Value : 0.5827          
##                                           
##             Sensitivity : 0.8199          
##             Specificity : 0.7798          
##          Pos Pred Value : 0.8462          
##          Neg Pred Value : 0.7456          
##              Prevalence : 0.5963          
##          Detection Rate : 0.4889          
##    Detection Prevalence : 0.5778          
##       Balanced Accuracy : 0.7998          
##                                           
##        'Positive' Class : CH              
## 
1-0.8037
## [1] 0.1963

As expected test error rates are identical.

Part C

Apply random forest (of your choice) and boosting (of your choice) for the data set in #9 and compare the results (test errors). Which one performs best?

Random Forest

set.seed(1237)
# Create Random forest
oj.cforest0 <- cforest(Purchase ~ ., 
                       data = oj.train,
                       control = cforest_unbiased(ntree = 500))

# Predict test results:
pcforest0 <- predict(oj.cforest0,
                    newdata = oj.test,
                    OOB = TRUE,
                    type = "response")

# Confusion Matrix:
confusionMatrix(pcforest0, oj.test$Purchase)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 144  32
##         MM  17  77
##                                           
##                Accuracy : 0.8185          
##                  95% CI : (0.7673, 0.8626)
##     No Information Rate : 0.5963          
##     P-Value [Acc > NIR] : 3.798e-15       
##                                           
##                   Kappa : 0.6145          
##                                           
##  Mcnemar's Test P-Value : 0.0455          
##                                           
##             Sensitivity : 0.8944          
##             Specificity : 0.7064          
##          Pos Pred Value : 0.8182          
##          Neg Pred Value : 0.8191          
##              Prevalence : 0.5963          
##          Detection Rate : 0.5333          
##    Detection Prevalence : 0.6519          
##       Balanced Accuracy : 0.8004          
##                                           
##        'Positive' Class : CH              
## 

Boosting

Preparing the datasets:

oj2 <- oj
oj2$Store7 <- as.numeric(oj2$Store7)

oj2.train <- oj2[train,]
oj2.test <- oj2[-train,]

Gradient boosting:

set.seed(1237)

# Creating OJ Purchase as the y-variable:
y <- oj2.train$Purchase
num.class = length(levels(y))
y <- as.numeric(y)-1 #y should start from 0 and numeric, not factor.

# Construct xgb.DMatrix object
dtrain <- xgb.DMatrix(as.matrix(oj2.train[,2:18]), label = y)

param <- list("objective" = "multi:softprob","num_class" = 2)    
          
#param <- list("objective" = "multi:softprob",    
#          "num_class" = 3,          
#          "num_parallel_tree" = 1, 
#          "eval_metric" = "mlogloss",    
#          "nthread" = 8,   
#          "max_depth" = 6,   
#          "eta" = 0.3, #learning rate    
#          "gamma" = 0,    
#          "subsample" = 1,    #subsample ratio
#          "colsample_bytree" = 1,  #subsample ratio of columns
#          "min_child_weight" = 1)

xfit1 <- xgboost(param=param, 
                 dtrain, 
                 nrounds=3) #compare with nround =2, num_parallel_tree seems to be 3 (?)
## [22:55:36] WARNING: amalgamation/../src/learner.cc:1115: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'multi:softprob' was changed from 'merror' to 'mlogloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
## [1]  train-mlogloss:0.535375 
## [2]  train-mlogloss:0.445079 
## [3]  train-mlogloss:0.382117
print(xfit1)
## ##### xgb.Booster
## raw: 28.4 Kb 
## call:
##   xgb.train(params = params, data = dtrain, nrounds = nrounds, 
##     watchlist = watchlist, verbose = verbose, print_every_n = print_every_n, 
##     early_stopping_rounds = early_stopping_rounds, maximize = maximize, 
##     save_period = save_period, save_name = save_name, xgb_model = xgb_model, 
##     callbacks = callbacks)
## params (as set within xgb.train):
##   objective = "multi:softprob", num_class = "2", validate_parameters = "TRUE"
## xgb.attributes:
##   niter
## callbacks:
##   cb.print.evaluation(period = print_every_n)
##   cb.evaluation.log()
## # of features: 17 
## niter: 3
## nfeatures : 17 
## evaluation_log:
##  iter train_mlogloss
##     1       0.535375
##     2       0.445079
##     3       0.382117
xgb.plot.tree(model = xfit1)
xgb.plot.multi.trees(model = xfit1)
## Column 2 ['No'] of item 2 is missing in item 1. Use fill=TRUE to fill with NA (NULL for list columns), or use.names=FALSE to ignore column names. use.names='check' (default from v1.12.2) emits this message and proceeds as if use.names=FALSE for  backwards compatibility. See news item 5 in v1.12.2 for options to control this message.
#xgb.dump(xfit1, with_stats = T)
pred = predict(xfit1,dtrain)
pred = matrix(pred,ncol=3,byrow=T)
## Warning in matrix(pred, ncol = 3, byrow = T): data length [1600] is not a sub-
## multiple or multiple of the number of rows [534]
pclass = apply(pred,1,which.max)
# table(oj2.train$Purchase,pclass)

# confusionMatrix(unique(oj2.train$Purchase)[pclass],oj2.train$Purchase)

mat = xgb.importance(feature_names = colnames(oj[,-5]),model = xfit1)
xgb.plot.importance(importance_matrix = mat)

Creating testing set confusion matrix:

# Creating OJ Purchase as the y-variable:
y2 <- oj2.test$Purchase
y2 <- as.numeric(y2)-1 #y should start from 0 and numeric, not factor.

dtest <- xgb.DMatrix(as.matrix(oj2.test[,2:18]), label = y2)
pred.test <- predict(xfit1,
                    newdata = dtest,
                    strict_shape = TRUE)

pred_labels <- factor(round(pred.test[2,])+1, labels = c("CH", "MM"))
# pred_labels <- max.col(pred.test) - 1
test_labels <- as.factor(oj2.test$Purchase)

confusionMatrix(pred_labels, oj2.test$Purchase)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 141  25
##         MM  20  84
##                                           
##                Accuracy : 0.8333          
##                  95% CI : (0.7834, 0.8758)
##     No Information Rate : 0.5963          
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.6512          
##                                           
##  Mcnemar's Test P-Value : 0.551           
##                                           
##             Sensitivity : 0.8758          
##             Specificity : 0.7706          
##          Pos Pred Value : 0.8494          
##          Neg Pred Value : 0.8077          
##              Prevalence : 0.5963          
##          Detection Rate : 0.5222          
##    Detection Prevalence : 0.6148          
##       Balanced Accuracy : 0.8232          
##                                           
##        'Positive' Class : CH              
## 

Conclusion

The XGBoost method produces the best test set accuracy, with accuracy of 83.3%.

Session Info

sessionInfo()
## R version 4.1.2 (2021-11-01)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19044)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=English_United States.1252 
## [2] LC_CTYPE=English_United States.1252   
## [3] LC_MONETARY=English_United States.1252
## [4] LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.1252    
## 
## attached base packages:
## [1] stats4    grid      stats     graphics  grDevices utils     datasets 
## [8] methods   base     
## 
## other attached packages:
##  [1] DiagrammeR_1.0.8   xgboost_1.5.0.2    party_1.3-9        strucchange_1.5-2 
##  [5] sandwich_3.0-1     zoo_1.8-9          modeltools_0.2-23  mvtnorm_1.1-3     
##  [9] randomForest_4.7-1 rattle_5.4.0       bitops_1.0-7       tibble_3.1.6      
## [13] rpart_4.1.16       caret_6.0-90       lattice_0.20-45    ISLR2_1.3-1       
## [17] ggplot2_3.3.5     
## 
## loaded via a namespace (and not attached):
##  [1] nlme_3.1-155         matrixStats_0.61.0   lubridate_1.8.0     
##  [4] RColorBrewer_1.1-2   tools_4.1.2          utf8_1.2.2          
##  [7] R6_2.5.1             DBI_1.1.2            colorspace_2.0-2    
## [10] nnet_7.3-17          withr_2.4.3          tidyselect_1.1.1    
## [13] compiler_4.1.2       scales_1.1.1         proxy_0.4-26        
## [16] stringr_1.4.0        digest_0.6.29        rmarkdown_2.11      
## [19] pkgconfig_2.0.3      htmltools_0.5.2      parallelly_1.30.0   
## [22] fastmap_1.1.0        highr_0.9            htmlwidgets_1.5.4   
## [25] rlang_0.4.12         rstudioapi_0.13      visNetwork_2.1.0    
## [28] jquerylib_0.1.4      generics_0.1.1       jsonlite_1.7.3      
## [31] dplyr_1.0.7          ModelMetrics_1.2.2.2 magrittr_2.0.1      
## [34] Matrix_1.4-0         Rcpp_1.0.8           munsell_0.5.0       
## [37] fansi_1.0.2          lifecycle_1.0.1      stringi_1.7.6       
## [40] multcomp_1.4-18      pROC_1.18.0          yaml_2.2.1          
## [43] MASS_7.3-55          plyr_1.8.6           recipes_0.1.17      
## [46] parallel_4.1.2       listenv_0.8.0        crayon_1.4.2        
## [49] splines_4.1.2        knitr_1.37           pillar_1.6.5        
## [52] future.apply_1.8.1   reshape2_1.4.4       codetools_0.2-18    
## [55] glue_1.6.1           evaluate_0.14        data.table_1.14.2   
## [58] vctrs_0.3.8          foreach_1.5.1        gtable_0.3.0        
## [61] purrr_0.3.4          tidyr_1.1.4          future_1.23.0       
## [64] assertthat_0.2.1     xfun_0.29            gower_0.2.2         
## [67] coin_1.4-2           prodlim_2019.11.13   libcoin_1.0-9       
## [70] e1071_1.7-9          class_7.3-20         survival_3.2-13     
## [73] timeDate_3043.102    iterators_1.0.13     lava_1.6.10         
## [76] globals_0.14.0       TH.data_1.1-0        ellipsis_0.3.2      
## [79] ipred_0.9-12

References

  1. James G, Witten D, Hastie T, Tibshirani R. An Introduction to Statistical Learning: With Applications in R. 1st ed. 2013, Corr. 7th printing 2017 edition. Springer; 2013.